package com.dhcc.core.modules.system.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dhcc.core.framework.annotion.BussinessLog;
import com.dhcc.core.framework.annotion.CacheClear;
import com.dhcc.core.framework.annotion.Permission;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.cache.SysCache;
import com.dhcc.core.framework.constant.Const;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.cache.permission.IPermissionCache;
import com.dhcc.core.modules.system.cache.role.IRoleCache;
import com.dhcc.core.modules.system.cache.role.RoleCache;
import com.dhcc.core.modules.system.entity.Role;
import com.dhcc.core.modules.system.service.IRoleService;
import com.dhcc.core.modules.system.service.IUserService;
import com.dhcc.core.modules.system.warpper.RoleWarpper;

/**
 * 角色控制器
 * 
 * @ClassName: RoleController
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:30:31
 */
@Controller
@RequestMapping("${sys.backendPath}/role")
public class RoleController extends BaseController {

    private static String PREFIX = "/backend/system/role/";

    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    /**
     * 跳转到角色列表页面
     */
    @RequestMapping
    public String index() {
        return PREFIX + "role.html";
    }

    /**
     * 跳转到添加角色
     */
    @Permission("role:add")
    @RequestMapping(value = "/role_add")
    public String roleAdd() {
        return PREFIX + "role_add.html";
    }

    /**
     * 跳转到修改角色
     */
    @Permission("role:update")
    @RequestMapping(value = "/role_edit/{roleId}")
    public String roleEdit(@PathVariable Long roleId, Model model) {
        if (CommonUtil.isEmpty(roleId)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        Role role = this.roleService.selectById(roleId);
        Object r = super.warpObject(new RoleWarpper(role));
        model.addAttribute("role",r);
        return PREFIX + "role_edit.html";
    }

    /**
     * 跳转到角色分配
     */
    @Permission("role:authority")
    @RequestMapping(value = "/role_assign/{resourceGroup}/{roleId}")
    public String roleAssign(@PathVariable("resourceGroup") String resourceGroup,
            @PathVariable("roleId") Long roleId, Model model) {
        if (CommonUtil.isEmpty(roleId)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("roleId", roleId);
        model.addAttribute("resourceGroup", resourceGroup);
        model.addAttribute("roleName", RoleCache.me().getRoleNameById(roleId));
        return PREFIX + "role_assign.html";
    }

    /**
     * 获取角色列表
     */
    @Permission("role:list")
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String roleName) {
        List<Map<String, Object>> roles = this.roleService.selectRoles(super.getParameter("roleName"));
        return super.warpObject(new RoleWarpper(roles));
    }

    /**
     * 角色新增
     */
    @RequestMapping(value = "/add")
    @BussinessLog(value = "添加角色")
    @Permission("role:add")
    @ResponseBody
    @CacheClear(IRoleCache.CACHE_NAME)
    public R add(@Valid Role role, BindingResult result) {
        if (result.hasErrors()) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        role.setId(null);
        role.init();
        this.roleService.insert(role);
        return R.ok();
    }

    /**
     * 角色修改
     */
    @RequestMapping(value = "/edit")
    @BussinessLog(value = "修改角色")
    @Permission("role:update")
    @ResponseBody
    @CacheClear(IRoleCache.CACHE_NAME)
    public R edit(@Valid Role role, BindingResult result) {
        if (result.hasErrors()) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        role.init();
        this.roleService.updateById(role);

        // 删除缓存
        SysCache.me().removeAll();
        return R.ok();
    }

    /**
     * 删除角色
     */
    @RequestMapping(value = "/remove")
    @BussinessLog(value = "删除角色")
    @Permission("role:delete")
    @ResponseBody
    @CacheClear({IRoleCache.CACHE_NAME,IPermissionCache.CACHE_NAME})
    public R remove(@RequestParam Long roleId) {
        if (CommonUtil.isEmpty(roleId)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }

        // 不能删除超级管理员角色
        if (roleId.equals(Const.ADMIN_ROLE_ID)) {
            throw new BizException(BizExceptionEnum.CANT_DELETE_ADMIN);
        }

        this.roleService.delRoleById(roleId);

        // 删除缓存
        SysCache.me().removeAll();
        return R.ok();
    }

    /**
     * 查看角色
     */
    @RequestMapping(value = "/view/{roleId}")
    @ResponseBody
    public R view(@PathVariable Long roleId) {
        if (CommonUtil.isEmpty(roleId)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        this.roleService.selectById(roleId);
        return R.ok();
    }

    /**
     * 配置权限
     */
    @RequestMapping("/set_authority/{resourceGroup}")
    @BussinessLog(value = "配置权限")
    @Permission("role:authority")
    @ResponseBody
    @CacheClear(IPermissionCache.CACHE_NAME)
    public R setAuthority(@PathVariable("resourceGroup") String resourceGroup,@RequestParam("roleId") Long roleId, @RequestParam("ids") String ids) {
        if (CommonUtil.isOneEmpty(roleId)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        this.roleService.setAuthority(roleId,resourceGroup, ids);
        return R.ok();
    }

    /**
     * 获取角色列表--不包含everyone
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree() {
        return RoleCache.me().getRoleTree();
    }


    /**
     * 获取角色列表--管理界面用(包含everyone)
     */
    @RequestMapping(value = "/treeEveryone")
    @ResponseBody
    public List<ZTreeNode> treeEveryone() {
        return RoleCache.me().getRoleTreeEveryone();
    }

}
